import { computed, ref } from 'vue'
import router from '@/router'
import { defineStore } from 'pinia'
import { USER_STORE } from '../constant'
import { getUserInfo } from '@/api/login'

export const useUserStore = defineStore(
  USER_STORE,
  () => {
    const token = ref<string>('')
    const openId = ref<string>('')
    const isBind = ref<string>('')
    const code = ref<string>('')
    const query = ref({})
    const login = async (state: any) => {}

    const getUserInfoAsync = async (code: string) => {
      const result = await getUserInfo(code)
      SET_USERINFO(result.data)
    }

    const logout = async () => {}

    const SET_TOKEN = (_token: string) => {
      token.value = _token
    }
    const SET_USERINFO = (result: any) => {
      const { openId: id, tokenFlag, token: _token } = result
      isBind.value = tokenFlag
      openId.value = id
      token.value = _token
      console.log(openId.value, isBind.value, _token, '拿到的信息')
    }
    const SET_BIND = (bind: string) => {
      isBind.value = bind
    }
    const SET_QUERY = (_query: any) => {
      console.log('触发')

      query.value = _query
    }
    const CLEAR_INFO = () => {
      token.value = ''
      isBind.value = ''
      query.value = {}
    }
    return {
      openId,
      token,
      isBind,
      code,
      query,
      login,
      logout,
      getUserInfoAsync,
      SET_TOKEN,
      SET_USERINFO,
      SET_BIND,
      CLEAR_INFO,
      SET_QUERY,
    }
  },
  {
    persist: {
      pick: ['token', 'openId', 'isBind', 'query'],
    },
  },
)
